package org.lcc.job;

import lombok.extern.slf4j.Slf4j;
import org.lcc.mapper.ExamRecordMapper;
import org.lcc.mapper.ScoreAnalysisMapper;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class ScoreAnalysisJob implements Job {

    @Autowired
    private ExamRecordMapper examRecordMapper;

    @Autowired
    private ScoreAnalysisMapper scoreAnalysisMapper;

    @Override
    @Transactional
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            log.info("考试分析任务已触发，当前时间：{}", LocalDateTime.now());
            log.info("开始考试分析...");
            System.out.println("开始考试分析...");
            // 1. 获取所有已批改但未分析的考试记录
            List<Map<String, Object>> examClassGroups = examRecordMapper.findGradedExamsWithoutAnalysis();

            for (Map<String, Object> group : examClassGroups) {
                Integer examId = (Integer) group.get("exam_id");
                Integer classId = (Integer) group.get("class_id");

                // 2. 检查该班级的所有考试记录是否都已完成批改
                boolean allGraded = examRecordMapper.checkAllExamRecordsGraded(examId, classId);
                if (!allGraded) {
                    continue;
                }

                // 3. 检查是否已存在分析记录
                boolean analysisExists = scoreAnalysisMapper.checkAnalysisExists(examId, classId);
                if (analysisExists) {
                    continue;
                }

                // 4. 计算分析数据
                Map<String, Object> analysisData = examRecordMapper.calculateExamAnalysis(examId, classId);

                // 5. 插入分析记录，正确处理BigDecimal转换
                Object avgScore = analysisData.get("average_score");
                Double averageScore = avgScore instanceof BigDecimal ?
                        ((BigDecimal) avgScore).doubleValue() :
                        avgScore instanceof Double ? (Double) avgScore : 0.0;

                Object highScore = analysisData.get("highest_score");
                Integer highestScore = highScore instanceof BigDecimal ?
                        ((BigDecimal) highScore).intValue() :
                        highScore instanceof Integer ? (Integer) highScore : 0;

                Object lowScore = analysisData.get("lowest_score");
                Integer lowestScore = lowScore instanceof BigDecimal ?
                        ((BigDecimal) lowScore).intValue() :
                        lowScore instanceof Integer ? (Integer) lowScore : 0;

                scoreAnalysisMapper.insertAnalysis(
                        examId,
                        classId,
                        averageScore,
                        highestScore,
                        lowestScore,
                        analysisData.get("analysis_data").toString()
                );

                log.info("已完成考试ID：{}，班级ID：{}的成绩分析", examId, classId);
            }

            log.info("考试分析任务执行完成");
        } catch (Exception e) {
            log.error("成绩分析任务执行失败", e);
            throw new JobExecutionException("成绩分析任务执行失败", e);
        }
    }
}